<?php

/**
 * Framework_Module_Register
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package 	Modules
 * @filesource
 */


/**
 * Framework_Module_Register
 *
 * @author 		Ian Szewczyk <roamzero@gmail.com>
 * @package 	Modules
 */
class Framework_Module_Register extends Framework_Module
{
	
    /**
     * __construct
     *
     * Initializes the module: sets the default presenter, the allowed
     * conrollers, and the allowed events
     *
     * @access 		public
     * @return 		void
     */
	public function __construct()
	{
			
		if (Framework::$request->isAjax()) {
			$this->presenter = 'Module';
		} else {
			$this->presenter = 'Smarty';
		}

		$this->controllers[] = 'Peopletab';
		parent::__construct();
	}

	/**
     * __default
     *
     *  Generates registration form
     *
     * @access 		public
     * @return 		mixed 		boolean true on success, PEAR_Error on failure
     */
	public function __default()
	{
		 

		$form = Framework_Quickform::factory('form', 'post', Framework::$request->getBaseHTTPPath().'/-/Register/');

		// Custom validation rules
		$form->registerRule('ownerDuplicate','function','checkForDuplicateOwners',$this);
		$form->registerRule('remoteLoginDuplicate','function','checkForDuplicateSiteUsers',$this);

		// Username field
		$form->addElement('text','userName','Select your public user name', 'class="textInput" id="userName"');
		$form->addRule('userName', 'User name is required', 'required');
		$form->addRule('userName','Duplicate Login Exists', 'remoteLoginDuplicate');
		 
		// loginName field
		$form->addElement('text','loginName','Select the name you want to log in under', 'class="textInput" id="loginName"');
		$form->addRule('loginName', 'Login name is required', 'required');
		$form->addRule('loginName','Duplicate Login Exists', 'ownerDuplicate');
		 
		// Password fields
		$form->addElement('password','userPassword','Password', 'class="textInput" id="userPassword"');
		$form->addRule('userPassword', 'Your password must be between 4 and 8 chars', 'rangelength', array(4,8));
		$form->addRule('userPassword', 'Required', 'required');
		 
		$form->addElement('password','userPassword2','Repeat Password', 'class="textInput" id="userPassword2"');
		$form->addRule('userPassword2', 'Required', 'required');
		 
		$form->addRule(array('userPassword', 'userPassword2'), 'The passwords do not match', 'compare', null);
		 
		$form->addElement('textarea','blurb','Blurb','class="textInput" id="blurb" COLS="40" ROWS="6"');
			
		// CAPTCHA
		$captcha = Framework_Quickform::captchaFiglet($form);
		if (PEAR::isError($captcha)) {
			return $captcha;
		}

		// Age verification
		$form->addElement('checkbox','chkAge',
		'',
		'I verify that I am 13 years or older and that I comply with this site\'s terms of service',
		'class="checkInput" id="chkAge"');
		$form->addRule('chkAge', 'Must meet minimum requirment', 'required');

		// Submit button
		$form->addElement('submit','btnSubmit','Register','class="button" id="btnSubmit"');
		// Cancel Button
		if (Framework::$request->isAjax()) {
			$form->addElement('submit','btnCancel','Cancel','class="button jqmClose" id="cancelButton"');
		}
		 
		// Filters
		$form->applyFilter('__ALL__','trim');
		$form->applyFilter('__ALL__','htmlentities');
		 
		$this->forms['Form'] = $form;
		 
		 

		// Process form
		if ($form->validate()) {
			$captcha['question']->destroy();
			$result = $form->process(array($this, 'process'));
		} else {
			$captcha['input']->setValue('');
			$this->tplFile = 'Register.tpl';
			return true;
		}
		return $result;

	}

	/**
     * process
     *
     * Processes the registration form data and creates new owner
     * in the database.
     *
     * @access 		public
     * @param  		array 		$data 		Form data to be processed
     * @return 		mixed 		Boolean true on success, PEAR_Error on failure
     */
	public function process($data)
	{
		 
		// Make keys
		require_once 'Crypt/RSA.php';
		require_once 'Crypt/RSA/Key.php';
		$primaryKeyPair = new Crypt_RSA_KeyPair(1024);
		$publicKey = $primaryKeyPair->getPublicKey();
		$privateKey = $primaryKeyPair->getPrivateKey();

		$siteUserTable = Framework_DB::tableFactory('SiteUser');
		$ownerTable = Framework_DB::tableFactory('Owner');
			
		// Register new owner
		$idSiteUser = $siteUserTable->nextId();
		$idOwner = $ownerTable->nextId();
			
		// Siteuser portion
		$siteUserTable->idSiteUser = $idSiteUser; // idSiteUser
		$siteUserTable->idOwner = $idOwner; // idOwner
		$siteUserTable->siteDomain = preg_replace('/^(www\.)(.+)/i', '$2', $_SERVER['HTTP_HOST']); //$_SERVER['HTTP_HOST']; // domain
		$siteUserTable->userName = $data['userName'];
		$siteUserTable->blurb = substr($data['blurb'], 0, 350);  // blurb
		$siteUserTable->publicKey = $publicKey->toString(); // publicKeyPrimary

		$result = $siteUserTable->save();
		if (PEAR::isError($result)) {
			return $result; // Framework Error
		}


		$ownerTable->idOwner = $idOwner; // idOwner
		$ownerTable->loginName = $data['loginName']; // loginName
		$ownerTable->pWord = md5($data['userPassword']); // pword
		$ownerTable->privateKey  = $privateKey->toString(); // privateKey
		$ownerTable->dateAdded = time();
		$ownerTable->defaultModule = 'Profile';
			
		$result = $ownerTable->save();
		if (PEAR::isError($result)) {
			return $result; // Framework Error
		}
		
		//TODO: make Register a user module maybe?
		
		// Logout
		//$this->session->destroy();
		
		// Autologin
		$userModule = new Framework_Module_User();
		
		$userModule->sessionLogin($idSiteUser);

		$this->setData('userName', $data['userName']);
		$this->setData('cp', 'http://'.Framework::$site->domain.'/'.$data['userName'].'/CP');
		$this->tplFile = 'RegSuccess.tpl';
		
		return true;
		 
	}

	/**
     * checkForDuplicateOwners
     *
     * Checks for a duplicate login name values in the database
     *
     * @access 		public
     * @param  		string 		$value		Login Name values to check
     * @return 		mixed 		boolean true if there are no duplicates, false if there are
     */
	public function checkForDuplicateOwners($value)
	{

		$ownerTable = Framework_DB::tableFactory('Owner');
		$queryArray = array(
			'sqlKey' => array(
				'select' => 'idOwner',
				'where'  => 'loginName = ?',
				'get'    => 'row'
		 	),
		 
			'params' => array($value)
		);
			
		$result = $ownerTable->select($queryArray);
			
		if (PEAR::isError($result)){
			die();
		}
		if (is_array($result))
		{
			return false;
		} else {
			return true;
		}
			
	}

	/**
     * checkForDuplicateSiteUsers
     *
     * Checks for duplicate user name values in the database
     *
     * @access 		public
     * @param  		string 		$value		 User Name value to check
     * @return 		mixed 		boolean true if there are no duplicates, false if there are
     */
	public function checkForDuplicateSiteUsers($value)
	{
		$siteUserTable = Framework_DB::tableFactory('SiteUser');
		$queryArray = array(
			'sqlKey' => array(
				'select' => 'idSiteUser',
				'where'  => 'userName = ? AND siteDomain = ?',
				'get'    => 'row'
			 ),
			'params' => array($value, $_SERVER['HTTP_HOST'])
		);
			
		$result = $siteUserTable->select($queryArray);
			
		if (PEAR::isError($result)) {
			die();
		}
		if (is_array($result))
		{
			return false;
		} else {
			return true;
		}
		 
	}


}